package com.means.polymerize.mainstay.metadata;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.means.polymerize.common.constants.ResultCode;
import com.means.polymerize.common.lang.DataResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 元数据读取器
 * <p>
 * 图像文件类型:
 * <p>
 * JPEG PNG WebP GIF ICO BMP TIFF PSD PCX RAW CRW CR2 NEF ORF RAF RW2 RWL SRW ARW DNG X3F
 * <p>
 * 视频文件类型:
 * <p>
 * MOV MP4 M4V 3G2 3GP 3GP
 * <p>
 * 元数据格式:
 * <p>
 * Exif IPTC XMP JFIF JFXX ICC 8BIM
 *
 * @author xuhaifeng
 * @since 2021.11.05
 */
@RestController
@RequestMapping("/metadata/info")
public class MetadataReader {

    /**
     * 读取信息
     *
     * @param request request
     * @return DataResult
     */
    @PostMapping("/read")
    public DataResult<List<Map<String, List<String>>>> read(@RequestParam("file") final List<MultipartFile> fileList) {
        if (CollUtil.isNotEmpty(fileList)) {
            final List<Map<String, List<String>>> metadataMapList = fileList.stream().filter(Objects::nonNull).map(file -> {
                final List<String> metadataList = ListUtil.toList();
                try {
                    ImageMetadataReader.readMetadata(file.getInputStream()).getDirectories().forEach(directory -> {
                        if (Objects.nonNull(directory)) {
                            directory.getTags().stream().filter(Objects::nonNull).forEach(tag ->
                                    metadataList.add(String.format("[%s] - %s = %s", directory.getName(), tag.getTagName(), tag.getDescription())));
                            if (directory.hasErrors()) {
                                directory.getErrors().forEach(error -> metadataList.add(String.format("ERROR: %s", error)));
                            }
                        }
                    });
                } catch (ImageProcessingException | IOException e) {
                    e.printStackTrace();
                }
                return MapUtil.builder(new HashMap<String, List<String>>(1))
                        .put(file.getOriginalFilename(), metadataList).build();
            }).toList();
            return DataResult.success(metadataMapList);
        }
        return DataResult.error(ResultCode.BAD_REQUEST.code, "请正确上传文件！");
    }

}
